package com.org.utils.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
 * jdbc连接器
 *
 */
public class JdbcHelper {
	/** 从平台查询应用要使用的数据库名 */
	private static String driverName = "com.mysql.jdbc.Driver";
	private static String URL = "jdbc:mysql://";
	/**
	 * ========================百度连接变量=End===============================
	 */
	private static JdbcHelper instance = null;
	private static Connection conn = null;
	private static Statement stmt = null;
	private static PreparedStatement pst = null;
	private static ResultSet rs = null;
	private static String Driver = "com.mysql.jdbc.Driver";// ConfigUtils.getProperty("jdbc.driver");
	//private static String Url = "jdbc:mysql://localhost:3306/dress?characterEncoding=utf8";// ConfigUtils.getProperty("jdbc.url");
	
	/**建立单例模式
	 * Single
	 * @return
	 */
	public static JdbcHelper getInstance() {
		if (instance == null) {
			synchronized (JdbcHelper.class) {
				instance = new JdbcHelper();
			}
		}
		return instance;
	}

	/**
	 * @return
	 */
	public static Connection getConnection(String url,  String userName, String password) {
		Connection conn = null;
		try {
			Class.forName(Driver);
			conn = DriverManager.getConnection(url, userName, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}

	/**
	 * 执行查询
	 * 
	 * @param sql
	 * @param args
	 */
	public static Object executeQuery(String url, String userName, String password, String sql, Object[] params, JdbcCallback callback) {
		// JSTL中提供的类,因此要导入JSTL的两个jar包
		Connection conn = null;
		PreparedStatement state = null;
		ResultSet rs = null;
		Object obj = null;
		try {
			url = "jdbc:mysql://" + url + "";
			conn = getConnection(url, userName, password);
			state = conn.prepareStatement(sql);
			if (params != null && params.length > 0) {
				for (int i = 0; i < params.length; i++) {
					state.setObject(i + 1, params[i]);
				}
			}
			rs = state.executeQuery();
			obj = callback.callback(rs);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			ReleaseSource(rs, state, conn);
		}
		return obj;
	}


	/**
	 * 释放资源...
	 * 
	 * @param rs
	 * @param st
	 * @param conn
	 */
	public static void ReleaseSource(ResultSet rs, Statement st, Connection conn) {
		try {
			if (rs != null)
				rs.close();
			if (st != null)
				st.close();
			if (conn != null)
				conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
